package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.aspectj.bridge.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class DishServiecImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.save(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> {
               flavor.setDishId(dishId);
            });
            dishFlavorMapper.save(flavors);
        }

    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        Integer start = (dishPageQueryDTO.getPage() - 1) * dishPageQueryDTO.getPageSize();
        Integer pageSize = dishPageQueryDTO.getPageSize();
        Long total = dishMapper.count(dishPageQueryDTO.getName(), dishPageQueryDTO.getCategoryId(), dishPageQueryDTO.getStatus());

        List<DishVO> dishVOS = new ArrayList<>();
        List<Dish> dishes = dishMapper.pageQuery(start, pageSize, dishPageQueryDTO.getName(), dishPageQueryDTO.getCategoryId(), dishPageQueryDTO.getStatus());

        dishes.forEach(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            String categoryName =  categoryMapper.getById(dish.getCategoryId());
            dishVO.setCategoryName(categoryName);

            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dish.getId());
            dishVO.setFlavors(flavors);
            dishVOS.add(dishVO);
        });
        PageResult pageResult = new PageResult(total, dishVOS);
        return pageResult;
    }

    @Transactional
    @Override
    public void deleteByDishId(List<Long> ids) {
        cleanCache("dish_*");

        //查看是否有菜品正在起售
        ids.forEach(id -> {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //查看是否有菜品与套餐关联
        ids.forEach(dishId -> {
            Setmeal setmeal = setmealDishMapper.getByDishId(dishId);
            if(setmeal != null) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });

        //删除菜品及其口味
        ids.forEach(dishId -> {
            dishMapper.deleteByDishId(dishId);
            dishFlavorMapper.deleteByDishId(dishId);
        });
    }

    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        String categoryName = categoryMapper.getById(dish.getCategoryId());

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        dishVO.setCategoryName(categoryName);
        return dishVO;
    }

    @Override
    public void update(DishDTO dishDTO) {
        cleanCache("dish_*");

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        Long dishId = dishDTO.getId();

        dishFlavorMapper.deleteByDishId(dishId);
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if(dishFlavors != null && !dishFlavors.isEmpty()) {
            dishFlavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.save(dishFlavors);
        }
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        cleanCache("dish_*");

        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }

    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        List<Dish> dishes = dishMapper.getByCategoryId(categoryId);
        return dishes;
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
